import { _decorator, Component, Node, Prefab, instantiate, director, BoxCollider2D, Contact2DType, PhysicsSystem2D, IPhysics2DContact, resources, Sprite, SpriteFrame, find, Label } from 'cc';
import { background_run } from './background_run';
const { ccclass, property } = _decorator;

@ccclass('playerCo')
export class playerCo extends Component {
    @property(Prefab)
    bulletPre:Prefab = null;

    count = 0

    start() {


        PhysicsSystem2D.instance.enable = true;

        let collider = this.getComponent(BoxCollider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            // collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
            // collider.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
            // collider.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
        }

        let self = this
        this.node.on(Node.EventType.TOUCH_MOVE,(event) =>{

            let p = this.node.getPosition();
            p.x += event.getUIDelta().x;
            p.y += event.getUIDelta().y;
            this.node.setPosition(p);
            // console.log(this.node.getPosition() + event.getUIDelta())
        })

        this.schedule(() =>{
            // console.log("wc")
            let bullet = instantiate(this.bulletPre);
            bullet.setParent(director.getScene().getChildByName('Canvas'));
            let p = this.node.getPosition()
            p.y += 70;
            bullet.setPosition(p);
        },0.5)

    }

    update(deltaTime: number) {
        
    }



    onBeginContact (selfCollider: BoxCollider2D, otherCollider: BoxCollider2D, contact: IPhysics2DContact | null) {
        // 只在两个碰撞体开始接触时被调用一次
        // console.log('onBeginContact');
        if(otherCollider.tag == 2){
                if(this.count == 0){
                this.count += 1;

                let label:Label = find("Canvas/game").getComponent(Label);
                label.string = "game over"

                resources.load("hero1_die/spriteFrame",SpriteFrame,(err,res) => {
    
                    this.getComponent(Sprite).spriteFrame = res;//这里也会出现线程安全问题
                })

                background_run.count = 1;



                setTimeout(() => {//此帧处理物理不能销毁，留到下一帧处理。
                // console.log(10)
                this.die()

            },1000)
            }
        }
        
        
    }
    die(){
        this.node.destroy();
    }
}


